package com.integrate.multiple.sources.conf.datasource;


import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author 刘志强
 * @date 2020/11/27 14:02
 * com.integrate.multiple.sources.mapper.consumer 生效范围
 */
@Configuration
@MapperScan(basePackages = {"com.integrate.multiple.sources.mapper.consumer"},sqlSessionFactoryRef = "consumerSqlSessionFactory")
public class ConsumerDataSourceConfiguration {

    @Autowired
    private Environment env;

    /**
     * 构建 consumer 数据源信息
     * @return
     */
    @Bean("consumerDatasourceModel")
    @ConfigurationProperties(prefix = "spring.datasource.consumer")
    public DatasourceModel consumerDatasourceModel() {
        DatasourceModel datasourceModel = new DatasourceModel();
        datasourceModel.setType(DruidDataSource.class);
        return datasourceModel;
    }

    /**
     * 配置数据源consumer
     * @Primary 默认装配的bean
     * @return
     */
    @Bean(name="consumerDataSource")
    @Primary
    public DataSource consumerDataSource(
            @Qualifier("poolProperties") Properties poolProperties,
            @Qualifier("consumerDatasourceModel") DatasourceModel consumerDatasourceModel) throws SQLException {
        DruidDataSource druidDataSource = (DruidDataSource) DataSourceBuilder.create()
                // 数据库 连接池类型 如果不设置类型默认类型为 com.zaxxer.hikari.HikariDataSource
                .type(consumerDatasourceModel.getType())
                // 驱动
                .driverClassName(consumerDatasourceModel.getDriverClassName())
                // 链接
                .url(consumerDatasourceModel.getUrl())
                // 账号
                .username(consumerDatasourceModel.getUserName())
                // 密码
                .password(consumerDatasourceModel.getPassword())
                .build();
        // 加载连接池配置信息
        druidDataSource.configFromPropety(poolProperties);
        // 初始化
        druidDataSource.init();
        return druidDataSource;
    }

    /**
     * consumer数据库的会话工厂
     * @param consumerDataSource
     * @param properties
     * @param resourceLoader
     * @return
     * @throws Exception
     */
    @Bean(name = "consumerSqlSessionFactory")
    @Primary
    public SqlSessionFactory consumerSqlSessionFactory(
            @Qualifier("consumerDataSource") DataSource consumerDataSource,
            @Qualifier("mybatisData") MybatisProperties properties,
            ResourceLoader resourceLoader) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(consumerDataSource);
        bean.setTypeAliasesPackage(properties.getTypeAliasesPackage());
        bean.setConfigLocation(resourceLoader.getResource(properties.getConfigLocation()));
        bean.setMapperLocations(properties.resolveMapperLocations());
        return bean.getObject();
    }

    /**
     * consumer数据库的会话模板
     * @param consumerSqlSessionFactory
     * @return
     */
    @Bean(name = "consumerSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate consumerSqlSessionTemplate(@Qualifier("consumerSqlSessionFactory") SqlSessionFactory consumerSqlSessionFactory) {
        return  new SqlSessionTemplate(consumerSqlSessionFactory);
    }

    /**
     * consumer数据库的事务
     * @param consumerDataSource
     * @return
     */
    @Bean(name = "consumerTransactionManager")
    @Primary
    public DataSourceTransactionManager consumerTransactionManager(@Qualifier("consumerDataSource") DataSource consumerDataSource){
        return new DataSourceTransactionManager(consumerDataSource);
    }

    /**
     * +定义配置文件
     * @return MybatisProperties
     */
    @Bean(name = "mybatisData")
    @ConfigurationProperties(prefix = "mybatis")
    @Primary
    public MybatisProperties mybatisProperties() {
        MybatisProperties mybatisProperties = new MybatisProperties();
        return mybatisProperties;
    }


    /**
     * 构建Properties
     * @return
     */
    @Bean("poolProperties")
    public Properties poolProperties() {
        String prefixPool = "spring.datasource.pool.";
        Properties prop = new Properties();
        prop.put("druid.initialSize", env.getProperty(prefixPool + "initialSize", String.class));
        prop.put("druid.maxActive", env.getProperty(prefixPool + "maxActive", String.class));
        prop.put("druid.minIdle", env.getProperty(prefixPool + "minIdle", String.class));
        prop.put("druid.maxWait", env.getProperty(prefixPool + "maxWait", String.class));
        prop.put("druid.poolPreparedStatements", env.getProperty(prefixPool + "poolPreparedStatements", String.class));
        prop.put("druid.maxPoolPreparedStatementPerConnectionSize", env.getProperty(prefixPool + "maxPoolPreparedStatementPerConnectionSize", String.class));
        prop.put("druid.validationQuery", env.getProperty(prefixPool + "validationQuery", String.class));
        prop.put("druid.validationQueryTimeout", env.getProperty(prefixPool + "validationQueryTimeout", String.class));
        prop.put("druid.testOnBorrow", env.getProperty(prefixPool + "testOnBorrow", String.class));
        prop.put("druid.testOnReturn", env.getProperty(prefixPool + "testOnReturn", String.class));
        prop.put("druid.testWhileIdle", env.getProperty(prefixPool + "testWhileIdle", String.class));
        prop.put("druid.timeBetweenEvictionRunsMillis", env.getProperty(prefixPool + "timeBetweenEvictionRunsMillis", String.class));
        prop.put("druid.minEvictableIdleTimeMillis", env.getProperty(prefixPool + "minEvictableIdleTimeMillis", String.class));
        prop.put("druid.filters", env.getProperty(prefixPool + "filters", String.class));
        return prop;
    }
}
